package me.malajis.equipmentprotect;

import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

public class DropListener implements Listener {
    private final Map<UUID, Boolean> IS_OPEN_MAP = new HashMap<>();

    @EventHandler
    public void onInventoryClick(InventoryClickEvent event) {
        if (event.isCancelled()) {
            return;
        }
        if (!(event.getWhoClicked() instanceof Player)) {
            return;
        }
        //背包中进行操作时返回true
        IS_OPEN_MAP.put(event.getWhoClicked().getUniqueId(), true);
    }

    @EventHandler
    public void onCloseInventory(InventoryCloseEvent event) {
        IS_OPEN_MAP.remove(event.getPlayer().getUniqueId());
    }

    //玩家丢弃物品时触发事件
    @EventHandler
    public void onDrop(PlayerDropItemEvent event) {
        if (Main.onEnable.getConfig().getBoolean("Config.DropListener")) {
            //获取触发者
            Player p = event.getPlayer();
            //打开了背包则结束
            if (IS_OPEN_MAP.getOrDefault(p.getUniqueId(), false)) {
                return;
            }
            //检测丢出是否带有附魔
            ItemMeta itemMeta = event.getItemDrop().getItemStack().getItemMeta();
            if (itemMeta != null && itemMeta.hasEnchants()) {
                //取消事件并发送提示
                event.setCancelled(true);
                p.sendMessage(Objects.requireNonNull(Main.onEnable.getConfig().getString("Message.droptip")).replace("&", "§"));
                p.playSound(p.getLocation(), Sound.ENTITY_VILLAGER_NO, 1, 1);
            }
        }
    }
}
